<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二维码扫描测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            text-align: center;
        }
        .video-container {
            position: relative;
            width: 100%;
            max-width: 400px;
            margin: 20px auto;
            border: 2px solid #ccc;
            border-radius: 8px;
            overflow: hidden;
        }
        video {
            width: 100%;
            height: auto;
        }
        .scan-frame {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 200px;
            border: 2px solid #667eea;
            border-radius: 8px;
            pointer-events: none;
        }
        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 10px;
        }
        button:hover {
            background: #5a6fd8;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin: 20px 0;
            padding: 10px;
            border-radius: 5px;
            min-height: 20px;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>二维码扫描功能测试</h1>
        <p>此页面用于测试摄像头权限和二维码识别功能</p>
        
        <div class="video-container" id="videoContainer" style="display: none;">
            <video id="video" autoplay playsinline></video>
            <div class="scan-frame"></div>
        </div>
        
        <div>
            <button id="startBtn" onclick="startScan()">开始扫描</button>
            <button id="stopBtn" onclick="stopScan()" disabled>停止扫描</button>
        </div>
        
        <div id="result" class="result"></div>
        
        <div style="margin-top: 30px; text-align: left;">
            <h3>测试说明：</h3>
            <ul>
                <li>点击"开始扫描"按钮</li>
                <li>浏览器会请求摄像头权限，请点击"允许"</li>
                <li>将包含MAC地址的二维码对准扫描框</li>
                <li>支持的MAC地址格式：
                    <ul>
                        <li>直接MAC地址：00:11:22:33:44:55</li>
                        <li>JSON格式：{"mac":"00:11:22:33:44:55"}</li>
                        <li>URL参数：http://example.com?mac=00:11:22:33:44:55</li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
    <script>
        let video = null;
        let stream = null;
        let scanning = false;
        
        function showResult(message, type = 'info') {
            const resultDiv = document.getElementById('result');
            resultDiv.textContent = message;
            resultDiv.className = `result ${type}`;
        }
        
        async function startScan() {
            try {
                showResult('正在请求摄像头权限...', 'info');
                
                // 检查浏览器支持
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('您的浏览器不支持摄像头功能');
                }
                
                // 请求摄像头权限
                stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode: 'environment',
                        width: { ideal: 1280 },
                        height: { ideal: 720 }
                    }
                });
                
                video = document.getElementById('video');
                video.srcObject = stream;
                
                document.getElementById('videoContainer').style.display = 'block';
                document.getElementById('startBtn').disabled = true;
                document.getElementById('stopBtn').disabled = false;
                
                showResult('摄像头已启动，请将二维码对准扫描框', 'success');
                
                scanning = true;
                scanQRCode();
                
            } catch (error) {
                console.error('摄像头启动失败:', error);
                
                let errorMessage = '无法访问摄像头';
                if (error.name === 'NotAllowedError') {
                    errorMessage = '请允许访问摄像头权限后重试';
                } else if (error.name === 'NotFoundError') {
                    errorMessage = '未检测到摄像头设备';
                } else if (error.name === 'NotSupportedError') {
                    errorMessage = '您的浏览器不支持摄像头功能';
                }
                
                showResult(errorMessage, 'error');
            }
        }
        
        function stopScan() {
            scanning = false;
            
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
            }
            
            document.getElementById('videoContainer').style.display = 'none';
            document.getElementById('startBtn').disabled = false;
            document.getElementById('stopBtn').disabled = true;
            
            showResult('扫描已停止', 'info');
        }
        
        function scanQRCode() {
            if (!scanning || !video) return;
            
            if (video.readyState === video.HAVE_ENOUGH_DATA) {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                
                canvas.height = video.videoHeight;
                canvas.width = video.videoWidth;
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                
                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const code = jsQR(imageData.data, imageData.width, imageData.height);
                
                if (code) {
                    const qrContent = code.data;
                    console.log('扫描到二维码:', qrContent);
                    
                    // 尝试提取MAC地址
                    let extractedMac = '';
                    const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
                    
                    if (macRegex.test(qrContent)) {
                        extractedMac = qrContent.toUpperCase().replace(/[-:]/g, ':');
                    } else {
                        try {
                            const jsonData = JSON.parse(qrContent);
                            if (jsonData.mac || jsonData.macAddress) {
                                extractedMac = (jsonData.mac || jsonData.macAddress).toUpperCase().replace(/[-:]/g, ':');
                            }
                        } catch {
                            const urlParams = new URLSearchParams(qrContent.split('?')[1] || '');
                            const macParam = urlParams.get('mac') || urlParams.get('macAddress');
                            if (macParam) {
                                extractedMac = macParam.toUpperCase().replace(/[-:]/g, ':');
                            }
                        }
                    }
                    
                    if (extractedMac && macRegex.test(extractedMac)) {
                        showResult(`扫描成功！提取到MAC地址: ${extractedMac}`, 'success');
                        stopScan();
                        return;
                    } else {
                        showResult(`二维码内容: ${qrContent}\n未找到有效的MAC地址`, 'error');
                        setTimeout(() => {
                            if (scanning) {
                                showResult('继续扫描中...', 'info');
                            }
                        }, 3000);
                    }
                }
            }
            
            if (scanning) {
                requestAnimationFrame(scanQRCode);
            }
        }
        
        // 页面卸载时停止扫描
        window.addEventListener('beforeunload', stopScan);
    </script>
</body>
</html>